import { handleWorkloadKey } from "@/utils";
import { ref } from "vue";
import { map } from "lodash";
import { getEdgeFullData } from "@/api/topoNodeDetail";
export default function useFullList({
  srcNodes,
  pageType,
  node:nodeInfo,
  onSearch,
  url,
  type,
  queryTime
}) {
  const fullList = ref([]);
  const allFullList = ref([]);
  const allDataExceptCount = ref(0);
  const buildFullParams = () => {
    const {from, to} = queryTime.value
    const node = nodeInfo.value
    console.log(pageType.value, 'pageType');

    if (pageType.value === "node") {

      const queryData = map(srcNodes.value, (node) => {
        return {
          masterIp: node.masterIp,
          namespace: node.namespace,
          workloadKind: node.workloadKind,
          workloadName: node.workloadName,
        };
      });
      const queryParams = {
        dstMasterIp: node.masterIp,
        dstNamespace: node.namespace,
        dstWorkload: node.workloadName,
        dstType: node.workloadKind,
        dstPod: type === "pod" ? node.podName : undefined,
        from,
        to,
      };
      return { queryData, queryParams };
    } else {
      console.log(node, 'edgeInfo');

      const {
        masterIp: srcMasterIp,
        namespace: srcNamespace,
        workloadKind: srcWorkloadKind,
        workloadName: srcWorkloadName,
      } = handleWorkloadKey(node.srcWorkloadKey || "");
      const {
        masterIp: dstMasterIp,
        namespace: dstNamespace,
        workloadKind: dstWorkloadKind,
        workloadName: dstWorkloadName,
      } = handleWorkloadKey(node.dstWorkloadKey || "");
      const queryData = [
        {
          masterIp: srcMasterIp,
          namespace: srcNamespace,
          workloadKind: srcWorkloadKind,
          workloadName: srcWorkloadName,
        },
      ];
      const queryParams = {
        dstMasterIp,
        dstNamespace,
        dstWorkload: dstWorkloadName,
        dstType: dstWorkloadKind,
        from,
        to,
      };
      return { queryData, queryParams };
    }
  };
  // 获取全量数据
  const getFullData = () => {
    const { queryData, queryParams } = buildFullParams();
    return getEdgeFullData(queryData, queryParams).then((res) => {
      // console.log(res.data, 'data');

      res.data.forEach((item) => {
        item.exceptionCount = item.slowCount + item.errorCount;
      });
      allFullList.value = [].concat(res.data || []);

      allDataExceptCount.value = res.data.reduce((prev, cur) => {
        return prev + cur.exceptionCount;
      }, 0);
      if (url) {
        onSearch(url, "full");
      } else {
        // console.log(res.data.data,  'data');

        fullList.value = res.data || [];
      }

      return Promise.resolve(allDataExceptCount.current);
    });
  };
  return {
    fullList,
    allFullList,
    allDataExceptCount,
    getFullData,
  };
}
